package com.heo.sso.server.dto;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

/**
 * @Author 刘康
 * @Date 2020-11-03 9:38
 * @Description TGT 票根， 一个用户对应一个票根，票根记录用户登录了哪些系统
 * @Revision
 **/
@Getter
@Slf4j
public class TicketGrantingTicket<T> {

    private static Map<String, TicketGrantingTicket> ticketGrantingTicketMap = new HashMap<>();

    private String id;

    // key为ticket value为service
    private Map<String, String> serviceMap = new HashMap<>();

    private T data;

    public TicketGrantingTicket(T data) {
        this.id = UUID.randomUUID().toString();
        this.data = data;
    }

    public String grantTicket() {
        // 使用UUID生成ticket
        String ticket = UUID.randomUUID().toString();
        // 保存到静态变量中,用于验证ticket是否有效（后续对接redis）
        ticketGrantingTicketMap.put(ticket, this);
        return ticket;
    }

    public static TicketGrantingTicket validTicket(String ticketId, String service) {
        log.info("验证ticket");
        log.info("ticket: {}", ticketId);
        log.info("service: {}",service);
        TicketGrantingTicket ticketGrantingTicket = ticketGrantingTicketMap.remove(ticketId);
        if (ticketGrantingTicket != null) {
            ticketGrantingTicket.serviceMap.put(ticketId, service);
        }
        return ticketGrantingTicket;
    }

}
